<template>
  <!-- 添加/编辑 对话框 -->
  <el-dialog :model-value="dialogFormVisible" title="分配角色" @close="handleClose">
    <!-- 表单 -->
    <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="账号：" prop="username">
        <el-input v-model="form.username" autocomplete="off" placeholder="请输入账号" style="font-size: 13px" />
      </el-form-item>
      <el-form-item label="姓名：" prop="nickName">
        <el-input v-model="form.nickName" autocomplete="off" placeholder="请输入姓名" style="font-size: 13px" />
      </el-form-item>
      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="form.email" autocomplete="off" placeholder="请输入邮箱" style="font-size: 13px" />
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input v-model="form.password" autocomplete="off" placeholder="请输入密码" style="font-size: 13px" type="password" />
      </el-form-item>
      <el-form-item label="备注：" prop="note">
        <el-input v-model="form.note" autocomplete="off" placeholder="请输入备注" style="font-size: 13px" :rows="3" type="textarea" />
      </el-form-item>
      <el-form-item label="是否启用：" prop="status">
        <el-radio-group v-model="form.status" class="ml-4">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <!-- 确定/取消 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button size="large" @click="cancelFn">取 消</el-button>
        <el-button size="large" type="primary" @click="confirmFn">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { admin } from '@/request/api'
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import { reactive, ref, watch } from 'vue'
const props = withDefaults(
  defineProps<{
    // 添加/编辑 对话框 显示/隐藏
    dialogFormVisible: boolean
    id: number
  }>(),
  { dialogFormVisible: false, id: 0 }
)
const emit = defineEmits<{
  (event: 'cancel'): void
  (event: 'confirm'): void
}>()
// 表单DOM
const ruleFormRef = ref<FormInstance>()
// 添加/编辑 对话框 form 表单信息
const form: IAdminRegisterParams = reactive({
  id: 0,
  username: '', // 用户名
  nickName: '', // 用户昵称
  email: '', // 邮箱
  password: '', // 密码
  note: '', // 备注
  status: 1, // 启用
})
// 监听id,获取指定用户的角色
watch(
  () => props.id,
  async (newVal) => {
    if (newVal === 0) {
      ruleFormRef.value?.resetFields()
    } else {
      let res = await admin.APIGetAdminInfoById(newVal)
      if (res.code === 200) {
        Object.assign(form, res.data)
      } else {
        ElMessage.error('错误！')
      }
    }
  }
)
// 取消 按钮
const cancelFn = () => {
  emit('cancel')
}
// 二次确认（添加）
const addUser = () => {
  ElMessageBox.confirm('此操作将添加当前用户信息, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      let res = await admin.APIAdminRegister(form)
      if (res.code === 200) {
        ElMessage.success('添加成功！')
        emit('confirm')
        ruleFormRef.value?.resetFields()
      } else {
        ElMessage.error(res.message)
      }
    })
    .catch(() => {})
}
// 二次确认（修改）
const editUser = () => {
  ElMessageBox.confirm('此操作将修改当前用户信息, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      let res = await admin.APIAdminUpdateById(form)
      if (res.code === 200) {
        ElMessage.success('修改成功！')
        emit('confirm')
      } else {
        ElMessage.error(res.message)
      }
    })
    .catch(() => {})
}
// 确定 按钮
const confirmFn = () => {
  ruleFormRef.value?.validate((isValid: boolean) => {
    if (isValid) {
      if (props.id === 0) {
        // 添加
        addUser()
      } else {
        // 编辑
        editUser()
      }
    } else {
      ElMessage.warning('校验失败!')
    }
  })
}
// Dialog 关闭的回调
const handleClose = () => {
  emit('cancel')
}
// 表单验证规则
const checkEmail = (rule: unknown, value: string, callback: (msg?: Error) => void) => {
  let emailRegexp = /^\w+[@]\w+\.\w{2,3}$/
  if (!emailRegexp.test(value)) {
    callback(new Error('请输入正确的邮箱地址！'))
  } else {
    callback()
  }
}
// form 校验规则
const rules = reactive<FormRules>({
  username: [{ required: true, message: '请输入账号！', trigger: 'blur' }],
  nickName: [{ required: true, message: '请输入姓名！', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱！', trigger: 'blur' },
    { validator: checkEmail, trigger: 'blur' },
  ],
  password: [{ required: true, message: '请输入密码！', trigger: 'blur' }],
})
</script>

<style lang="less" scoped>
// 对话框
</style>
